package com.wt.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wt.admin.entity.WqunAccount;
import com.wt.admin.entity.WqunComment;
import com.wt.admin.entity.rewentity.RewComment;
import com.wt.admin.service.WqunAdminService;
import com.wt.admin.service.WqunCommentService;
import com.wt.admin.service.impl.WqunAdminServiceImpl;
import com.wt.admin.service.impl.WqunCommentServiceImpl;
import com.wt.commonutils.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 评论表 前端控制器
 * </p>
 *
 * @author wt
 * @since 2023-09-13
 */
@RestController
@RequestMapping("/wqunComment")
public class WqunCommentController {

    @Autowired
    WqunCommentService wqunCommentService = new WqunCommentServiceImpl();

    @Autowired
    WqunAdminService wqunAdminService = new WqunAdminServiceImpl();


    //查询指定文章的评论
    @ApiOperation("查询指定文章的评论")
    @GetMapping("/findCommentById/{blogUid}")
    @PreAuthorize("hasAnyAuthority('wqunComment:findCommentById')")
    public R findCommentById(@PathVariable("blogUid") String blogUid){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("blog_uid",blogUid);
        queryWrapper.orderByDesc("created_time");
        List<WqunComment> findCommentById = wqunCommentService.list(queryWrapper);

        //封装评论信息
        List<RewComment> rewCommentList = new ArrayList<>();
        RewComment rewComment = new RewComment();
        //一级评论添加
        for (int i = 0; i < findCommentById.size(); i++) {
            WqunComment wqunComment = findCommentById.get(i);
            if(wqunComment.getToUid() == null){//没有指定回复的评论id则说明是一级评论
                rewComment = getRewComment(wqunComment);
                List<RewComment> list = new ArrayList<>();
                rewComment.setReplyInfo(list);
                rewCommentList.add(rewComment);
            }
        }

        //二级评论添加，逆转评论，使得一级评论按时间从下到上，回复评论从下倒下
        for (int i = findCommentById.size() - 1; i >= 0; i--) {
            WqunComment wqunCommentSec = findCommentById.get(i);
            if(wqunCommentSec.getToUid() != null){//存在指定回复的评论id则说明是二级评论
                for (int j = 0; j<rewCommentList.size(); j++) {//循环，找到对应的一级评论，将二次评论放到对应的位置
                    RewComment rewCommentFirst = rewCommentList.get(j);
                    if(wqunCommentSec.getFirstComment().equals(rewCommentFirst.getId())){//找到对应的一级评论，将二次评论放到对应的位置
                        rewComment = getRewComment(wqunCommentSec);//将二级评论封装

                        rewCommentList.get(j).getReplyInfo().add(rewComment);
                        rewCommentList.set(j,rewCommentFirst);//修改该元素
                    }
                }
            }
        }
        return R.ok().data("findCommentById",rewCommentList);
    }
    public RewComment getRewComment(WqunComment wqunComment){//封装评论信息
        RewComment rewComment = new RewComment();
        rewComment.setId(wqunComment.getId());//标识
        rewComment.setUserUid(wqunComment.getUserUid());
        //通过id获取评论人信息
        rewComment.setUsername(wqunAdminService.getById(wqunComment.getUserUid()).getNickName());
        rewComment.setReplyName(
                wqunComment.getToUserUid()==null?null:wqunAdminService.getById(wqunComment.getToUserUid()).getNickName());
        rewComment.setAvatar(wqunAdminService.getById(wqunComment.getUserUid()).getAvatar());

        rewComment.setToUid(wqunComment.getToUid()==null?null:wqunComment.getToUid());//回复某条评论的uid
        rewComment.setToUserUid(wqunComment.getToUserUid()==null?null:wqunComment.getToUserUid());//回复某个人的uid
        rewComment.setContent(wqunComment.getContent());//评论内容
        rewComment.setSource(wqunComment.getSource());//评论来源
        rewComment.setType(wqunComment.getType());//评论类型
        rewComment.setCreatedTime(wqunComment.getCreatedTime());//创建时间

        return rewComment;
    }


    //添加评论
    @ApiOperation("添加评论")
    @PostMapping("/addComment")
    @PreAuthorize("hasAnyAuthority('wqunComment:addComment')")
    public R addComment(@RequestBody WqunComment  wqunComment){
        boolean res = wqunCommentService.save(wqunComment);
        return res?R.ok().message("添加成功"):R.error().message("添加失败");
    }

    //删除评论
    @ApiOperation("删除评论")
    @GetMapping("/deleteComment/{id}")
    @PreAuthorize("hasAnyAuthority('wqunComment:deleteComment')")
    public R deleteComment(@PathVariable("id") String id){

        QueryWrapper<WqunComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("to_uid",id);
        boolean remove = wqunCommentService.remove(queryWrapper);//先删除回复该评论的评论
        boolean res = wqunCommentService.removeById(id);//删除该评论
        return remove && res?R.ok().message("删除成功"):R.error().message("删除失败");
    }


    //评论总数
    @ApiOperation("评论总数")
    @GetMapping("/allCommentNum")
    @PreAuthorize("hasAnyAuthority('wqunComment:allCommentNum')")
    public R allCommentNum(){
        QueryWrapper queryWrapper = new QueryWrapper();
        int allCommentNum = wqunCommentService.count(queryWrapper);
        return allCommentNum!=0?R.ok().data("allCommentNum",allCommentNum):R.error();
    }

    //指定文章评论总数
    @ApiOperation("评论总数")
    @GetMapping("/commentNumById/{id}")
    @PreAuthorize("hasAnyAuthority('wqunComment:commentNumById')")
    public R commentNumById(@PathVariable("id") String id){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("blog_uid",id);
        int commentNumById = wqunCommentService.count(queryWrapper);
        return R.ok().data("commentNumById",commentNumById);
    }


}

